/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.IllegalOrphanException;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Church;
import pt.iasd.youthshelter.datamodel.service.ChurchController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=ChurchController.class)
public class ChurchJpaController implements Serializable, ChurchController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(Church church) {
        if (church.getPathfinderList() == null) {
            church.setPathfinderList(new ArrayList<Pathfinder>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            List<Pathfinder> attachedPathfinderList = new ArrayList<Pathfinder>();
            for (Pathfinder pathfinderListPathfinderToAttach : church.getPathfinderList()) {
                pathfinderListPathfinderToAttach = em.getReference(pathfinderListPathfinderToAttach.getClass(), pathfinderListPathfinderToAttach.getId());
                attachedPathfinderList.add(pathfinderListPathfinderToAttach);
            }
            church.setPathfinderList(attachedPathfinderList);
            em.persist(church);
            for (Pathfinder pathfinderListPathfinder : church.getPathfinderList()) {
                Church oldChurchIdOfPathfinderListPathfinder = pathfinderListPathfinder.getChurchId();
                pathfinderListPathfinder.setChurchId(church);
                pathfinderListPathfinder = em.merge(pathfinderListPathfinder);
                if (oldChurchIdOfPathfinderListPathfinder != null) {
                    oldChurchIdOfPathfinderListPathfinder.getPathfinderList().remove(pathfinderListPathfinder);
                    em.merge(oldChurchIdOfPathfinderListPathfinder);
                }
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(Church church) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Church persistentChurch = em.find(Church.class, church.getId());
            List<Pathfinder> pathfinderListOld = persistentChurch.getPathfinderList();
            List<Pathfinder> pathfinderListNew = church.getPathfinderList();
            List<String> illegalOrphanMessages = null;
            for (Pathfinder pathfinderListOldPathfinder : pathfinderListOld) {
                if (!pathfinderListNew.contains(pathfinderListOldPathfinder)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Pathfinder " + pathfinderListOldPathfinder + " since its churchId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Pathfinder> attachedPathfinderListNew = new ArrayList<Pathfinder>();
            for (Pathfinder pathfinderListNewPathfinderToAttach : pathfinderListNew) {
                pathfinderListNewPathfinderToAttach = em.getReference(pathfinderListNewPathfinderToAttach.getClass(), pathfinderListNewPathfinderToAttach.getId());
                attachedPathfinderListNew.add(pathfinderListNewPathfinderToAttach);
            }
            pathfinderListNew = attachedPathfinderListNew;
            church.setPathfinderList(pathfinderListNew);
            church = em.merge(church);
            for (Pathfinder pathfinderListNewPathfinder : pathfinderListNew) {
                if (!pathfinderListOld.contains(pathfinderListNewPathfinder)) {
                    Church oldChurchIdOfPathfinderListNewPathfinder = pathfinderListNewPathfinder.getChurchId();
                    pathfinderListNewPathfinder.setChurchId(church);
                    pathfinderListNewPathfinder = em.merge(pathfinderListNewPathfinder);
                    if (oldChurchIdOfPathfinderListNewPathfinder != null && !oldChurchIdOfPathfinderListNewPathfinder.equals(church)) {
                        oldChurchIdOfPathfinderListNewPathfinder.getPathfinderList().remove(pathfinderListNewPathfinder);
                        em.merge(oldChurchIdOfPathfinderListNewPathfinder);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = church.getId();
                if (findChurch(id) == null) {
                    throw new NonexistentEntityException("The church with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Church church;
            try {
                church = em.getReference(Church.class, id);
                church.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The church with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Pathfinder> pathfinderListOrphanCheck = church.getPathfinderList();
            for (Pathfinder pathfinderListOrphanCheckPathfinder : pathfinderListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Church (" + church + ") cannot be destroyed since the Pathfinder " + pathfinderListOrphanCheckPathfinder + " in its pathfinderList field has a non-nullable churchId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(church);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<Church> findChurchEntities() {
        return findChurchEntities(true, -1, -1);
    }

    @Override
    public List<Church> findChurchEntities(int maxResults, int firstResult) {
        return findChurchEntities(false, maxResults, firstResult);
    }

    private List<Church> findChurchEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Church.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public Church findChurch(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(Church.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getChurchCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Church> rt = cq.from(Church.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
